<template>
  <div>
    <el-form ref="ruleForm" class="base_form" :model="submitForm" :rules="rules" label-width="200px">
      <el-form-item label="商品品类" prop="category_id">
        <el-select v-model="submitForm.category_id" placeholder="请选择商品品类" @change="categoryChange">
          <el-option v-for="item in categoryList" :key="item.category_id" :label="item.name" :value="item.category_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="goods_name">
        <el-input v-model="submitForm.goods_name" style="width:100%" maxlength="50" show-word-limit placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="推广关键字">
        <el-input v-model="submitForm.spread_title" style="width:100%" maxlength="50" show-word-limit placeholder="请输入推广关键字，以中文逗号隔开" />
      </el-form-item>
      <el-form-item label="商品参数">
        <div class="flex flex-wrap params_wrap">
          <template v-for="(param, index) in goodsParams">
            <div :key="index">
              <label><i v-if="param.must_is" class="required-icon" style="margin-right:5px">*</i>{{ param.field_title }}:</label>
              <template v-if="param.field_type == 1">
                <!-- 文本框 -->
                <el-input v-model="param.field_val" placeholder="请输入" />
              </template>
              <template v-if="param.field_type == 2">
                <!-- 下拉单选 -->
                <el-select v-model="param.field_val" placeholder="请选择">
                  <el-option v-for="(item, indexRadio) in param.field_list" :key="indexRadio" :label="item" :value="item" />
                </el-select>
              </template>
              <template v-if="param.field_type == 3">
                <!-- 下拉多选 -->
                <el-select v-model="param.field_val" placeholder="请选择" multiple>
                  <el-option v-for="(item, indexMore) in param.field_list" :key="indexMore" :label="item" :value="item" />
                </el-select>
              </template>
            </div>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="新旧" prop="new_grade">
        <el-radio-group v-model="submitForm.new_grade">
          <el-radio v-for="(val, key) in initData.new_grade" :key="key" :label="key">{{ val }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="租赁标签">
        <div v-for="item in initData.rent_label" :key="item" class="inline-block pointer rent_tag" :class="{ 'active': isTagCheck(item) }" @click="handleTagClick(item)">
          <span class="inline-block color-666">{{ item }}</span>
          <span class="inline-block text-center"><i v-if="isTagCheck(item)" class="el-icon-check blue-font v-middle check_icon" /></span>
        </div>
      </el-form-item>
      <el-form-item label="商品封面" prop="imgurl">
        <crop-upload
          ref="coverUpload"
          show-type="photo"
          :fix-scale="true"
          :is-square="true"
          :always-crop="true"
          :fixed-box="false"
          :init-val="submitForm.imgurl"
          wrapper-width="120px"
          wrapper-height="120px"
          :photo-width="120"
          :photo-height="120"
          :auto-crop-width="150"
          :auto-crop-height="150"
          cropper-width="400px"
          cropper-height="400px"
          dialog-width="600px"
          :min-width="750"
          :min-height="750"
          :enlarge="5"
          @setVal="setUrl"
        />
        <div class="color-999">注：尺寸为750*750px及以上正方形，图片要求为纯白色底图
          <el-popover placement="right" width="400" trigger="hover">
            <div class="img_exp">
              <h5>商品封面图片示例</h5>
              <div class="exp_wrap">
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp1.png')" />
                  <span><i class="green-font el-icon-success" />推荐</span>
                </p>
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp2.png')" />
                  <span><i class="red-font el-icon-error" />不推荐</span>
                </p>
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp3.png')" />
                  <span><i class="red-font el-icon-error" />不推荐</span>
                </p>
              </div>
              <p class="red-font">注：图片要求750*750像素以上的正方形图片；<br>注：上传封面图片要求纯白色底图；<br>注：精品纯白色底图可上首页推荐位！</p>
            </div>
            <el-button slot="reference" type="text">图片示例></el-button>
          </el-popover>
        </div>
      </el-form-item>
      <el-form-item label="商品图片" prop="carousel_img">
        <crop-upload
          ref="cropUpload"
          :fix-scale="true"
          :sort="true"
          :multiple="true"
          :always-crop="true"
          show-type="photo"
          :fixed-box="false"
          :is-square="true"
          :init-val="submitForm.carousel_img"
          wrapper-width="120px"
          wrapper-height="120px"
          :auto-crop-width="150"
          :auto-crop-height="150"
          cropper-width="400px"
          cropper-height="400px"
          dialog-width="600px"
          :enlarge="5"
          :max-num="8"
          :photo-width="120"
          :photo-height="120"
          :min-width="750"
          :min-height="750"
          @setVal="bannerChange"
        />
      </el-form-item>
      <el-form-item label="商品详情">
        <div class="editor_wrap">
          <text-editor v-model="submitForm.goods_content" />
        </div>
      </el-form-item>
      <el-form-item label="租赁方式" prop="pact_type">
        <el-radio-group v-model="submitForm.pact_type">
          <el-radio v-for="(val, key) in initData.pact_type" :key="key" :label="key">{{ val }}</el-radio>
        </el-radio-group>
        <p class="type_tip">
          <template v-if="submitForm.pact_type == 1">
            <span>固定租期的芝麻信用授权可扣款金额=商品套餐押金+总租金</span><br>商品设置固定租期后，承租人须待租赁期满后才能退还租赁物。固定租期无法使用花呗分期功能。
          </template>
          <template v-if="submitForm.pact_type == 2">
            <span>租完即送的芝麻信用授权可扣款金额=总租金</span><br>商品设置租完即送后，租赁期内承租人不得单方面解除协议提前退还租赁物，承租人须按订单约定按期支付租金。租完即送可使用花呗分期功能。
          </template>
          <template v-if="submitForm.pact_type == 3">
            <span>随租随还的芝麻信用授权可扣款金额=商品套餐押金+总租金</span><br>商品设置随租随还后，承租人可以随时退还租赁物。随租随还无法使用花呗分期功能。
          </template>
        </p>
      </el-form-item>
      <el-form-item label="服务城市" prop="province">
        <el-cascader v-model="submitForm.province" clearable filterable placeholder="请选择" :options="areaList" :props="optionProps" separator="-" />
      </el-form-item>
      <el-form-item label="租赁地址">
        <el-select v-model="submitForm.service_address" clearable placeholder="请选择">
          <el-option v-for="(item, index) in initData.shop_address" :key="index" :label="item.address" :value="item.address" />
        </el-select>
        <!-- 待添加
        <p
          class="color-999 inline-block"
          style="margin-left:15px"
        >没有租赁地址？点击添加<el-button type="text">租赁地址</el-button>
        </p> -->
      </el-form-item>
      <!-- <el-form-item label="运费">
        <el-input
          v-model="submitForm.transfer_cost"
          clearable
          @input="val=>changeNumberInput('transfer_cost',val)"
        >
        </el-input>
      </el-form-item> -->
      <el-form-item label="配送方式" prop="send_out" style="margin-bottom:0px">
        <div class="flex align-center">
          <label class="text-right" style="width:40px;margin-right:20px"><span class="required-icon">*</span>寄出</label>
          <el-radio-group v-model="submitForm.send_out">
            <el-radio v-for="(val, key) in initData.send_out" :key="key" :label="key">{{ val }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="flex align-center">
          <label class="text-right" style="width:40px;margin-right:20px">归还</label>
          <el-radio-group v-model="submitForm.return">
            <el-radio v-for="(val, key) in initData.return" :key="key" :label="key">{{ val }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>
    <div class="fix-footer-btns">
      <el-button size="small" @click="$router.go(-1)">返回</el-button>
      <el-button v-if="$hasMethod('#save')" size="small" type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script>
import cropUpload from '@/components/cropUpload'
import textEditor from '@/components/wangEditor'
import { getShopCategory, getGoodsAreas, getGoodsRentData, getGoodsParameter, getGoodsData, editGoodsData } from '@/api/audit'
export default {
  components: { cropUpload, textEditor },
  // props: ['editId'],
  props: {
    editId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      submitForm: {
        category_id: null,
        goods_name: '',
        spread_title: '',
        new_grade: '100',
        rent_label: [],
        imgurl: '',
        carousel_img: [],
        goods_content: '',
        pact_type: '1',
        province: [],
        service_address: '',
        send_out: '1',
        return: '1',
        transfer_cost: ''
      },
      rules: {
        carousel_img: [
          { required: true, message: '请上传商品图片', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择服务城市', trigger: 'change' }
        ],
        category_id: [
          { required: true, message: '请选择商品品类', trigger: 'change' }
        ],
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        imgurl: [
          { required: true, message: '请上传商品封面', trigger: 'change' }
        ],
        new_grade: [
          { required: true, message: '请选择新旧程度', trigger: 'change' }
        ]
      },
      areaList: [], // 服务城市
      adsList: [], // 租赁地址
      categoryList: [], // 品类列表
      optionProps: {
        value: 'id',
        label: 'name',
        expandTrigger: 'hover',
        children: 'sub'
      },
      initData: {
        new_grade: {}, // 新旧程度
        rent_label: [], // 标签
        pact_type: [], // 租赁方式
        send_out: {}, // 寄出
        return: {}, // 归还
        shop_address: [] // 租赁地址
      },
      goodsParams: [] // 商品参数
    }
  },
  mounted() {
    this.init()
    this.getData()
  },
  methods: {
    // 获取品类对应的商品参数
    async categoryChange(val) {
      if (!val) {
        return
      }
      await getGoodsParameter(val).then(res => {
        this.goodsParams = []
        for (const item of res) {
          item.field_val = ''
          item.field_list = item.field_list.split(',')
          this.goodsParams.push({ ...item })
        }
      })
    },
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 检查商品参数必填项
          for (const item of this.goodsParams) {
            if (item.must_is && (!item.field_val || item.field_val.length === 0)) {
              this.$message({
                message: '商品参数' + item.field_title + '必填',
                type: 'warning'
              })
              return
            }
          }
          const data = { goods_id: this.editId, ...this.submitForm, operation_type: 3 }
          data.rent_label = data.rent_label.join(',')
          data.province_id = data.province[0]
          data.show_ity = data.province[1]
          data.carousel_img = data.carousel_img.join(',')
          data.custom = this.goodsParams.map(item => { return { 'field_title': item.field_title, 'field_val': item.field_type !== 3 ? item.field_val : item.field_val.join(',') } })
          delete data.province
          // console.log(data);
          editGoodsData(data).then(res => {
            this.$router.push({ name: 'goodsSuccess', params: { goodsId: this.editId }})
          })
        } else {
          this.$message({
            message: '请检查表单错误',
            type: 'error'
          })
          return false
        }
      })
    },
    changeNumberInput(key, value) {
      const pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
      // 不符合正整数时
      if (!pattern.test(value)) {
        // input 框绑定的内容为空
        this.submitForm[key] = ''
      }
    },
    bannerChange(val, type) {
      if (type === 'sort') {
        this.submitForm.carousel_img = val
        return
      }
      if (type === 'del') {
        this.submitForm.carousel_img.splice(val, 1)
      } else {
        this.submitForm.carousel_img.push(val)
      }
      this.$refs.cropUpload.sortList = this.submitForm.carousel_img
    },
    setUrl(val) {
      this.submitForm.imgurl = val
    },
    handleTagClick(tag) {
      const index = this.submitForm.rent_label.findIndex(item => item === tag)
      if (index > -1) {
        this.submitForm.rent_label.splice(index, 1)
      } else {
        this.submitForm.rent_label.push(tag)
      }
    },
    // 判断标签是否选中
    isTagCheck(tag) {
      return this.submitForm.rent_label.findIndex(item => item === tag) > -1
    },
    init() {
      getShopCategory(this.editId).then(res => {
        this.categoryList = res || []
      })
      getGoodsAreas().then(res => {
        this.areaList = res ? res[0].sub : []
      })
      getGoodsRentData().then(res => {
        if (res) {
          this.initData = res
        }
      })
    },
    getData() {
      // 编辑
      getGoodsData(this.editId).then(async res => {
        for (const key in this.submitForm) {
          if (key === 'carousel_img') {
            this.submitForm[key] = res.carousel_images ? res.carousel_images.split(',') : []
            this.$refs.cropUpload.sortList = this.submitForm.carousel_img
          } else if (key === 'goods_name') {
            this.submitForm[key] = res.title
          } else if (key === 'province') {
            this.submitForm[key] = res.province_id && res.show_ity ? [res.province_id, res.show_ity] : res.province_id ? [res.province_id] : []
          } else if (key === 'rent_label') {
            this.submitForm[key] = res.rent_label.split(',')
          } else if (key === 'pact_type') {
            this.submitForm[key] = res.pact_type + ''
          } else if (key === 'return') {
            this.submitForm[key] = res.convey_type2 + ''
          } else if (key === 'send_out') {
            this.submitForm[key] = res.convey_type1 + ''
          } else if (res[key]) {
            this.submitForm[key] = res[key]
          }
        }
        // console.log(this.submitForm)
        await this.categoryChange(res.category_id)
        for (const item of res.attribute) {
          for (const param of this.goodsParams) {
            if (item.field_title === param.field_title) {
              param.field_val = param.field_type === 3 ? item.field_val.split(',') : item.field_val
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.editor_wrap {
  width: 700px;
  /deep/.text {
    height: 360px;
    overflow: auto;
  }
}
.base_form {
  padding: 30px 120px 30px 0;
}
.params_wrap {
  width: 100%;
  padding: 20px;
  background-color: #fafafa;
  label {
    display: inline-block;
    width: 120px;
    text-align: right;
    margin-right: 10px;
  }
  &>div {
    margin-bottom: 10px;
  }
}
.type_tip {
  color: #999999;
  line-height: 22px;
  span {
    color: #ff4146;
  }
}
.rent_tag {
  height: 30px;
  line-height: 28px;
  border: 1px solid #eeeeee;
  border-radius: 3px;
  span:first-child {
    padding-left: 5px;
    padding-right: 5px;
    background: #d2d2d2;
  }
  span:last-child {
    width: 35px;
  }
  &:not(:last-of-type) {
    margin-right: 15px;
  }
  &.active {
    border: 1px solid $mainBlue;
    span:first-child {
      color: #ffffff;
      background: $mainBlue;
    }
  }
  .check_icon {
    font-size: 26px;
    font-weight: bold;
  }
}
.exp_wrap {
  display: flex;
  margin-top: 18px;
  margin-bottom: 18px;
  .item {
    display: flex;
    width: 33%;
    align-items: center;
    flex-direction: column;
    .el-image {
      border: 1px solid #eeeeee;
    }
    span {
      margin-top: 10px;
      i {
        font-size: 20px;
        vertical-align: middle;
        margin-right: 3px;
      }
    }
  }
}
.fix-footer-btns {
  .el-divider {
    background-color: #eeeeee;
    width: 95%;
    margin: 15px auto;
  }
}
</style>
